#include "stdafx.h"
#include "OnWorldGui.h"

#include "2DUtils.h"
#include "Unit.h"
#include "GlobalAppData.h"

#include "Globals.h"

static XMVECTOR healthBarColor = XMLoadFloat4(&Color::GREEN);

static void drawSelectionRect()
{
	if(g_playerContext->DrawingSelectionRect)
	{
		Point p1 = g_playerContext->DrawSelectionRectStart;
		Point p2 = g_playerContext->DrawSelectionRectEnd;
		uint minX = min(p1.X, p2.X);
		uint maxX = max(p1.X, p2.X);
		uint minY = min(p1.Y, p2.Y);
		uint maxY = max(p1.Y, p2.Y);
		mgfx::Utils2D::drawRect(minX, minY, maxX - minX, 1, XMLoadFloat4(&Color::GREEN));
		mgfx::Utils2D::drawRect(minX, maxY, maxX - minX, 1, XMLoadFloat4(&Color::GREEN));
		mgfx::Utils2D::drawRect(minX, minY, 1, maxY - minY, XMLoadFloat4(&Color::GREEN));
		mgfx::Utils2D::drawRect(maxX, minY, 1, maxY - minY, XMLoadFloat4(&Color::GREEN));
	}
}

void OnWorldGui::draw(const XMFLOAT4X4 & viewProjMatrix, const XMFLOAT3 & cameraUpVector, const XMFLOAT3 & cameraRightVector)
{
	uint scrWid = mcore::GlobalAppData::Instance.ScreenWidth;
	uint scrHei = mcore::GlobalAppData::Instance.ScreenHeight;

	for(uint i = 0; i < g_playerContext->SelectedUnits.size(); i++)
	{
		const Unit & unit = *g_playerContext->SelectedUnits[i];

		XMVECTOR healthMarkerPos = XMLoadFloat3(&unit.Position) - XMVector3Normalize(XMLoadFloat3(&cameraUpVector)) * unit.getBoundingSphere().Radius * 0.8f;
		healthMarkerPos = XMVector3Transform(healthMarkerPos, XMLoadFloat4x4(&viewProjMatrix));
		float xPos = XMVectorGetX(healthMarkerPos) / XMVectorGetW(healthMarkerPos);
		float yPos = XMVectorGetY(healthMarkerPos) / XMVectorGetW(healthMarkerPos);

		//XMVECTOR healthMarkerExtentLeft = XMLoadFloat3(&unit.Position) - XMVector3Normalize(XMLoadFloat3(&cameraRightVector)) * unit.getBoundingSphere().Radius;
		//healthMarkerExtentLeft = XMVector3Transform(healthMarkerExtentLeft, XMLoadFloat4x4(&viewProjMatrix));
		//float xPos = XMVectorGetX(healthMarkerExtentLeft) / XMVectorGetW(healthMarkerExtentLeft);
		//float yPos = XMVectorGetY(healthMarkerExtentLeft) / XMVectorGetW(healthMarkerExtentLeft);

		int halfWidth = (int)(unit.getBoundingSphere().Radius * 500.0f / XMVectorGetW(healthMarkerPos));

		mgfx::Utils2D::drawRect(
			(uint)((xPos * 0.5f + 0.5f) * scrWid) - halfWidth,
			(uint)((-yPos * 0.5f + 0.5f) * scrHei) - 2,
			halfWidth * 2, 4, healthBarColor);
	}

	drawSelectionRect();
}
